package edu.zhuoxun.blogserver.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.zhuoxun.blogserver.entity.*;
import edu.zhuoxun.blogserver.map.UserMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class UserController {
    @Resource
    public UserMapper userMapper;
    @GetMapping("/api/user/page")
    @ResponseBody
    public Result<Page<User>> getAllUsers(int page, int size){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        Page<User> userPage = new Page<>(wrapper, userMapper, page, size);
        userPage.getList().forEach(user -> user.setPassword(null));
        Result<Page<User>> result = new Result<>();
        result.setCode(200);
        result.setMessage("OK");
        result.setData(userPage);
        return result;
    }
    @PostMapping("/api/user/delete")
    @ResponseBody
    public Result<Void> deleteUsers(@RequestBody List<User> list){
        Result<Void> result = new Result<>();
        boolean hasRoot = list.stream().anyMatch(user -> user.getId() == 1);
        if (hasRoot) {
            result.setCode(500);
            result.setMessage("超级管理员无法删除");
        } else {
            userMapper.deleteBatchIds(list.stream().map(User::getId).collect(Collectors.toList()));
            result.setCode(200);
            result.setMessage("OK");
        }
        return result;
    }

    @PostMapping("/api/user/update")
    @ResponseBody
    public Result<Void> updateUser(@RequestBody UserRoles userRoles){
        Result<Void> result = new Result<>();
        userMapper.updateById(userRoles.getUser());
        userMapper.deleteHasRoles(userRoles.getUser());
        userMapper.insertHasRoles(userRoles);
        result.setCode(200);
        result.setMessage("OK");
        return result;
    }
}
